package cmd

import (
	"fmt"
	"os"
	"os/signal"
	"runtime"
	"syscall"

	"github.com/spf13/cobra"
	"go.uber.org/zap"

	"ldaccount/internal"
	"ldaccount/internal/conf"
	"ldaccount/pkg/log"
	"ldaccount/pkg/middleware"
)

func initLDAccount() error {

	// logger 初始化
	logger := log.NewFactory(zapLogger)
	// 配置文件初始化
	cfg, err := conf.Init(configFilePath)
	if err != nil {
		logger.Bg().Fatal(fmt.Sprintf("failed to Init Config: %s", err.Error()))
	}
	if cfg == nil {
		logger.Bg().Fatal(fmt.Sprintf("failed to Init Config"))
	}
	// 链路追踪
	_, tracingClose := middleware.TracingInit("ldaccount", metricsFactory, logger)
	defer func() {
		_ = tracingClose.Close()
	}()
	runtime.GOMAXPROCS(cfg.Base.MaxProc)

	// 初始化服务
	server := internal.NewServer(logger, cfg)
	server.Run()

	// signal
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
	s := <-c
	logger.Bg().Info("report get a signal", zap.String("signal", s.String()))
	switch s {
	case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
		server.Close()
		return nil
	case syscall.SIGHUP:
	default:
		return nil
	}
	return nil
}

/// mLogicCmd member logic start cmd
var ldAccountCmd = &cobra.Command{
	Use:   "account",
	Short: "量子原力账号",
	Long:  "量子原力统一账号",
	RunE: func(cmd *cobra.Command, args []string) error {
		return initLDAccount()
	},
}

func init() {
	RootCmd.AddCommand(ldAccountCmd)
}
